package wxdb.ui;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class CreateDB extends JDialog{
	
	private JButton createButton = new JButton("Create");
	private JButton cancelButton = new JButton("Cancel");
	
	private JLabel dbLabel = new JLabel("DB Name :");
	private JTextField dbnameInput = new JTextField(10);
	
	private JPanel pane = new JPanel();
	
	Font fon = new Font("Dialog",Font.PLAIN,15);
	
	private String usr = "";
	
	
	void buildConstraints(GridBagConstraints gbc,int gx, int gy, int gw, int gh, int wx, int wy){
		gbc.gridx = gx;			
		gbc.gridy = gy;			
		gbc.gridwidth = gw;		
		gbc.gridheight = gh;	
		gbc.weightx = wx;		
		gbc.weighty = wy;		
	}
	
	
	private void setMyPane(){
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints constraints = new GridBagConstraints();
		pane.setLayout(gridbag);
		
		buildConstraints(constraints,0,0,3,1,1,1);
		gridbag.setConstraints(dbLabel, constraints);
		pane.add(dbLabel);
		
		buildConstraints(constraints,3,0,3,1,1,1);
		gridbag.setConstraints(dbnameInput, constraints);
		dbnameInput.setFont(fon);
		pane.add(dbnameInput);

		buildConstraints(constraints,0,2,2,1,1,1);
		gridbag.setConstraints(createButton, constraints);
		pane.add(createButton);

		buildConstraints(constraints,2,2,2,1,1,1);
		gridbag.setConstraints(cancelButton, constraints);
		pane.add(cancelButton);

		setLocation(200,80);
		setContentPane(pane);
	}
	

	private void initListener(){
		ActListener actListener = new ActListener();
		createButton.addActionListener(actListener);
		cancelButton.addActionListener(actListener);
	}
	
	class ActListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			if(e.getSource() == createButton)
				createRun();
			if(e.getSource() == cancelButton)
				cancelRun();
		}
	}
	
	private void cancelRun(){
		this.dispose();
	}
	
	private void createRun(){
		String dbname = dbnameInput.getText();
		if(dbname.equals("")){
			JOptionPane.showMessageDialog(null,"Inpute your DB name please","Error" ,JOptionPane.ERROR_MESSAGE);
			return;
		}else{
			Global.storageMgr().createDB(dbname);
			Global.changeRights(usr, dbname+";");
			Global.mg = new Management(dbname);
			this.dispose();
		}
	}
	
	public CreateDB(String username){
		usr = username;
		setTitle("CreateDB");
		setSize(500,200);
		initListener();
		setMyPane();
		setVisible(true);
		setResizable(false);
	}
}
